<?php
$xh = $_COOKIE['xh'];
$pwd = $_COOKIE['pwd'];
$rememberMe = $_COOKIE['rememberMe'];
if ($_POST){
    try {
        //echo '<pre>',print_r($_POST,true),'</pre>';
        if ($_POST['rememberMe']){//记住登录信息
            setcookie('xh',$_POST['xh'],time()+7*24*2222);
            setcookie('pwd',$_POST['pwd'],time()+7*24*2222);
            setcookie('rememberMe',$_POST['rememberMe'],time()+7*24*2222);
        }else{//不用记住登录信息
            setcookie('xh');
            setcookie('pwd');
            setcookie('rememberMe');
        }
        $db = new PDO("mysql:host=localhost; dbname=db2;", 'root', 'root');
        $db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
        $ps = $db ->prepare('select * from students where xh=? and pwd=?');
        $ps -> execute([$_POST['xh'],$_POST['pwd']]);
        $r = $ps -> fetch();
        //var_dump($r);
        if ($r === false) throw new Exception('你输入的用户名或口令不正确');
        header('Location: index.php');
        return;
    }catch (Throwable $e){
        $msg = $e -> getMessage();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户登录</title>
    <style>
        h1{
            color:red;
        }
        input{
            padding: 10px;
            margin:6px;
            border-radius: 6px;
        }
        .msg{
            color:red;
            margin: 20px 0;
        }
    </style>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
    学号：<input type="text" name="xh" value="<?=$_POST['xh']??$xh?>"><br>
    密码：<input type="password" name="pwd" value="<?=$_POST['pwd']??$pwd?>"><br>
    <input type="checkbox" name="rememberMe" <?=$_POST?($_POST['rememberMe']?'checked':''):($rememberMe=='on'?'checked':'')?>>记住我的信息一周<br>
    <div class="msg"><?=$msg?></div>
    <input type="submit" value="提交数据">
</form>
</body>
</html>
